#!/usr/bin/env python
# python <(curl -fsSL https://gitee.com/Astro-Lee/storage/raw/master/openwrt/build-openwrt) -h
from subprocess import getstatusoutput
import requests, re, tarfile, os, sys


def download_file():
    try:
        print('正在下载 openwrt 源代码', end=', ')
        # 获取最新版本tag
        latest = requests.get(url = 'https://github.com/openwrt/openwrt/releases/latest',
                        allow_redirects = True,
                        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.36'}).text
        latest_tag = re.findall(r'/openwrt/openwrt/tree/(v[0-9\.]+)', latest)[0]

        # 下载 
        download = requests.get(url = f'https://github.com/openwrt/openwrt/archive/refs/tags/{latest_tag}.tar.gz',
                        allow_redirects = True,
                        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.36'}).content
        with open('openwrt.tar.gz', 'wb') as f:
            f.write(download)

        # 解压
        tarfile.open('openwrt.tar.gz').extractall(path = './')

        # 删除压缩包
        getstatusoutput('rm -rf openwrt.tar.gz')
        # 重命名
        getstatusoutput(f'mv openwrt-{latest_tag[1:]} openwrt-latest')
        print('下载 openwrt 源代码完成')
    except Exception as e:
        print('下载 openwrt 源代码失败.', e)


def feeds_update():
    print('正在更新 feeds', end=', ')
    # 更新 feeds
    update = getstatusoutput('./scripts/feeds update -a')
    # 写入日志
    if update[0] == 0:
        print('feeds 更新成功')
    else:
        print('feeds 更新失败')

    with open('feeds_update.log', 'w') as f:
        f.write(update[1])

def feeds_install():
    print('正在安装 feeds', end=', ')
    # 安装 feeds
    install = getstatusoutput('./scripts/feeds install -a')
    # 写入日志
    if install[0] == 0:
        print('feeds 安装成功')
    else:
        print('feeds 安装失败')

    with open('feeds_install.log', 'w') as f:
        f.write(install[1])

def make_menuconfig(path: str):
    # 如果是网址，则下载 openwrt-latest/.config
    # 下载 .config 文件
    if r'://' in path:
        try:
            config = requests.get(url = path,
                            allow_redirects = True,
                            headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.36'}).content
            with open('.config', 'wb') as f:
                f.write(config)
            print('下载 .config 成功')
        except Exception as e:
            print('下载 .config 失败.', e)
    elif os.path.exists(f'{path}'):
            # 如果是文件路径，复制到 openwrt-latest/.config
            # 复制 .config 文件
            cp_flie = getstatusoutput(f'cp -f {path} .config')
            if cp_flie[0] == 0:
                print('复制 .config 成功')
            else:
                print('复制 .config 失败.', cp_flie[1])
    else:
        print('Not found .config file, please run "make menuconfig" to generate it.')

def make():
    print('正在编译 openwrt', end=', ')
    # 编译
    make_task = getstatusoutput(f'make V=s -j{os.cpu_count()-1}')
    # 写入日志
    if make_task[0] == 0:
        print('编译成功')
    else:
        print('编译失败')
    with open('make.log', 'w') as f:
        f.write(make_task[1])

if __name__ == '__main__':
    print(f'Running with args {sys.argv}')
    import argparse
    parser = argparse.ArgumentParser()

    parser.add_argument('-c', '--config', dest='config', 
                        type=str, default='.config',
                        help='path or URL of the config file (.config)')
    parser.add_argument('-dl', '--download', dest='download', action='store_true', default=False, 
    help='download source code & make')

    args = parser.parse_args()

    if args.download:
        download_file()

    os.chdir('openwrt-latest')
    print('工作路径:', os.getcwd())

    feeds_update()

    feeds_install()

    make_menuconfig(args.config)

    make()